package com.xrtn.service.impl;

import com.jxcell.View;
import com.xrtn.bean.*;
import com.xrtn.mapper.*;
import com.xrtn.page.Page;
import com.xrtn.service.IUserService;
import com.xrtn.utils.DateUtils;
import com.xrtn.utils.ExcelTool;
import com.xrtn.utils.HttpUtils;
import com.xrtn.utils.ObjUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * Created by tu_pei on 2018/3/12.
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private TUserInfoMapper userInfoMapper;
    @Autowired
    private TPatientInfoMapper patientInfoMapper;
    @Autowired
    private TPatientInitMapper patientInitMapper;
    @Autowired
    private TOrderInfoMapper orderInfoMapper;
    @Autowired
    private AccountOrderInfoMapper accountOrderInfoMapper;
    @Autowired
    private AccountUserInfoMapper accountUserInfoMapper;
    @Autowired
    private TCardUsrRelMapper cardUsrRelMapper;
    @Autowired
    private TCouponUsrRelMapper couponUsrRelMapper;
    @Autowired
    private SysUserInfoMapper sysUserInfoMapper;
    @Autowired
    private SysRoleInfoMapper roleInfoMapper;
    @Autowired
    private TBookingInfoMapper bookingInfoMapper;
    @Autowired
    private TPatientTreatmentMapper patientTreatmentMapper;
    @Autowired
    private TUserTreatmentRelMapper userTreatmentRelMapper;
    @Autowired
    private TBackcardInfoMapper backcardInfoMapper;
    @Autowired
    private TOrderGoodsDetailMapper goodsDetailMapper;
    @Autowired
    private TOrderServiceDetailMapper serviceDetailMapper;
    @Autowired
    private TPatientHistoryMapper patientHistoryMapper;
    @Autowired
    private TUserConclusionRelMapper userConclusionRelMapper;
    @Autowired
    private TUserDiseaseRelMapper userDiseaseRelMapper;
    @Autowired
    private TUserPointRelMapper userPointRelMapper;

    @Override
    public Page selectUserPageList(Page page, Map<String, Object> params) {

        String fromPage = (String) params.get("fromPage");
        if ("0".equals(fromPage)) { // 从会员中心查询
            // 校验查询人员是否有查看全部门店的权限
            boolean canSeeAll = false;
            SysUserInfo loginUser = (SysUserInfo) params.get("loginUser");
            if (ObjUtils.isNotEmpty(loginUser)) {

                List<Map<String, Object>> userFunctionList = roleInfoMapper.selectRoleLists(loginUser.getUserRole());
                List<String> groupList = new ArrayList<>();

                for (Map<String, Object> functionMap : userFunctionList) {
                    groupList.add(functionMap.get("menuName").toString());
                    if (Integer.parseInt(functionMap.get("functionId").toString()) == 45) {
                        canSeeAll = true;
                    }
                }
            }

            if (!canSeeAll) {
                params.put("seeBookingSubclinicId", loginUser.getSubclinicId());
            }
        }

        //时间分类：0，1，2，3，4：全部，一，二，三，超过三个月未到店

        Object timeType = params.get("timeType");

        if (ObjUtils.isNotEmpty(timeType)) {
            String timeTypes = timeType.toString();
            if (timeTypes.equals("1")) {
                params.put("datediffDay", 30);
                params.put("timeType", 1);
            }
            if (timeTypes.equals("2")) {
                params.put("datediffDay", 60);
                params.put("timeType", 2);
            }
            if (timeTypes.equals("3")) {
                params.put("datediffDay", 90);
                params.put("timeType", 3);
            }
            if (timeTypes.equals("4")) {
                params.put("datediffDay", 91);
                params.put("timeType", 4);
            }
        }
        page.setItems(userInfoMapper.selectUserPageList(page, params));
        return page;
    }

    /**
     * 查询用户详情
     *
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> selectUserInfo(Integer userId) {

        Map<String, Object> retMap = new HashMap<>();

        Map<String, Object> userMap = userInfoMapper.selectUserDetail(userId);

        if (ObjUtils.isEmpty(userMap)) {
            return null;
        }

        List<Map<String, Object>> patientList = patientInfoMapper.selectBySysUserId(userId);

        for (Map<String, Object> patientMap : patientList) {

            if (ObjUtils.isNotEmpty(patientMap.get("patientBirthday"))) {
                String patientBirthday = patientMap.get("patientBirthday").toString();
                Calendar date = Calendar.getInstance();
                date.setTime(new Date());
                Calendar birthStr = Calendar.getInstance();
                try {
                    birthStr.setTime(DateUtils.parse(patientBirthday, DateUtils.YYYY_MM_DD));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                String birthDay = DateUtils.getDate(date, birthStr);
                patientMap.put("birthdayStr", birthDay);
            }
        }

        userMap.put("userId", userId);
        //订单
//        Page page = Page.newBuilder(1, 100);
//        List<Map<String,Object>> orderDetail = orderInfoMapper.selectSysOrderPageList(page,userMap);
        //消费
        //userMap.put("payWay","0");
        List<Map<String, Object>> accountList = accountUserInfoMapper.selectUserAccountList(userMap);
        BigDecimal account = new BigDecimal(0);
        for (Map<String, Object> accountMap : accountList) {
            account = account.add(new BigDecimal(accountMap.get("accountCost").toString()));
        }
        //userMap.put("payWay",null);
        //计次卡
        userMap.put("cardType", 5);
        List<Map<String, Object>> cardList = cardUsrRelMapper.selectUserUseCardList(userMap);
        Integer cardNum = 0;

        if (cardList.size() > 0) {
            for (Map<String, Object> card : cardList) {
                Integer cardType = Integer.parseInt(card.get("cardType").toString());
                if (cardType == 5) {
                    cardNum += Integer.parseInt(card.get("cardLeftTime").toString());
                }

            }
        }
        //次卡明细
        List<Map<String, Object>> cardDetailList = cardUsrRelMapper.selectUserAccountCardList(userMap);
        //优惠券
        userMap.put("isUsed", 0);
        List<Map<String, Object>> couponList = couponUsrRelMapper.selectByUserIdAndIsUsed(userMap);

        retMap.put("userInfo", userMap);
        retMap.put("patientList", patientList);
//        retMap.put("orderDetail", orderDetail);
        retMap.put("accountList", accountList);
        retMap.put("account", account);
        retMap.put("cardList", cardList);
        retMap.put("cardNumber", cardNum);
        retMap.put("cardDetailList", cardDetailList);
        retMap.put("couponList", couponList);
        retMap.put("couponNumber", couponList.size());

        return retMap;
    }

    @Override
    public Integer saveUserAccount(SysUserInfo loginSysUser, Map<String, Object> params) {
        // 更新会员余额
        Integer userId = (Integer) params.get("userId");
        TUserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        BigDecimal rechargeAccount = (BigDecimal) params.get("rechargeAccount");

        if (rechargeAccount.add(userInfo.getUserAccount()).doubleValue() < 0) {
            return -10; // 扣款失败
        }

        userInfo.setUserAccount(rechargeAccount.add(userInfo.getUserAccount()));
        userInfoMapper.updateByPrimaryKeySelective(userInfo);

        // 生成流水
        AccountUserInfo record = new AccountUserInfo();
        record.setUserId(userId);
        record.setAccountDesc((String) params.get("rechargeDesc"));
        record.setAccountCost(rechargeAccount);
        record.setBalancePayCost(rechargeAccount);
        record.setAccountNo(ObjUtils.getAccountNo());
        record.setCardType(0);
        record.setAccountType(1);
        record.setPayWay((Integer) params.get("payWay"));
        record.setCashierId(loginSysUser.getUserId());
        record.setSubclinicId(loginSysUser.getSubclinicId());

        int res = accountUserInfoMapper.insertSelective(record);

        return res;
    }

    @Override
    public Integer deleteUserInfo(Integer userId) {
        TUserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        if (ObjUtils.isEmpty(userInfo)) {
            return 1; // 用户不存在
        }

        // 查询是否有已完成订单
        Map<String, Object> stateParams = new HashMap<>();
        stateParams.put("userId", userId);
        stateParams.put("orderState", 0);
        List<TOrderInfo> orderList = orderInfoMapper.selectByMaps(stateParams);
        if (orderList.size() > 0) {
            return 2; // 有已完成订单
        }

        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);

        // 删除病历相关
        patientHistoryMapper.deleteByUserId(userId); // 删除病史档案
        userConclusionRelMapper.deleteByUserId(userId); // 删除诊断结论
        userDiseaseRelMapper.deleteByUserId(userId); // 删除用户病状
        userPointRelMapper.deleteByUserId(userId); // 删除用户穴位

        // 删除病历
        List<TPatientTreatment> patientTreatments = patientTreatmentMapper.selectByUserId(params);
        for (TPatientTreatment treatment : patientTreatments) {
            Integer treatmentId = treatment.getTreatmentId();
            userTreatmentRelMapper.deleteByTreatmentId(treatmentId); // 删除病历得分
            patientTreatmentMapper.deleteByPrimaryKey(treatmentId);
        }

        // 删除用户订单相关
        List<TOrderInfo> orderInfos = orderInfoMapper.selectByMaps(params);
        for (TOrderInfo orderInfo : orderInfos) { // （by orderID)
            accountOrderInfoMapper.deleteByOrderId(orderInfo.getOrderId()); // 删除订单流水
            params.put("orderId", orderInfo.getOrderId());
            goodsDetailMapper.deleteByMap(params); // 删除商品详情
            serviceDetailMapper.deleteByMap(params); // 删除服务详情
        }
        orderInfoMapper.deleteByUserId(userId); // 删除订单
        cardUsrRelMapper.deleteByUserId(userId); // 删除计次卡
        backcardInfoMapper.deleteByUserId(userId); // 删除退款信息
        accountUserInfoMapper.deleteByUserId(userId); // 删除账户流水

        // 删除预约
        bookingInfoMapper.deleteByUserId(userId);

        // 删除患者
        List<TPatientInfo> patientList = patientInfoMapper.selectByMap(params);
        for (TPatientInfo patientInfo : patientList) {
            Integer patientId = patientInfo.getPatientId();
            patientInfoMapper.deleteByPrimaryKey(patientId);
            patientInitMapper.deleteByPatientId(patientId);
        }

        // 删除用户
        userInfoMapper.deleteByPrimaryKey(userId);
        return 0;
    }

    @Override
    public void exportUserList(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        Page pages = Page.newBuilder(1, Integer.MAX_VALUE);
        List<Map<String, Object>> maps = userInfoMapper.selectUserPageList(pages, params);
        System.out.println(maps.size());


        //加密
        View m_view = new View();
        try {
            m_view.setNumSheets(1);
            m_view.setSheet(0);
            m_view.setSheetName(0, "会员表");
            m_view.setTextAsValue(0, 0, "姓名");
            m_view.setTextAsValue(0, 1, "电话");
            m_view.setTextAsValue(0, 2, "就诊次数");
            m_view.setTextAsValue(0, 3, "订单累计消费(元)");
            m_view.setTextAsValue(0, 4, "累计充值(元)");
            m_view.setTextAsValue(0, 5, "获课门店");
            m_view.setTextAsValue(0, 6, "上次消费时间");
            m_view.setTextAsValue(0, 7, "余额");

            for (int j = 1; j <= maps.size(); j++) {
                Object userName = maps.get(j - 1).get("userName");
                Object userPhone = maps.get(j - 1).get("userPhone");
                Object orderNumber = maps.get(j - 1).get("orderNumber");
                Object orderCost = maps.get(j - 1).get("orderCost");
                Object rechargeCost = maps.get(j - 1).get("rechargeCost");
                Object subclinicName = maps.get(j - 1).get("subclinicName");
                Object orderTime = maps.get(j - 1).get("orderTime");
                Object userAccount = maps.get(j - 1).get("userAccount");
                m_view.setText(j, 0, String.valueOf(userName));
                m_view.setText(j, 1, String.valueOf(userPhone));
                m_view.setText(j, 2, String.valueOf(orderNumber));
                m_view.setText(j, 3, String.valueOf(orderCost));
                m_view.setText(j, 4, String.valueOf(rechargeCost));
                m_view.setText(j, 5, String.valueOf(subclinicName));
                m_view.setText(j, 6, String.valueOf(orderTime));
                m_view.setText(j, 7, String.valueOf(userAccount));

            }
            try {
                m_view.write("/usr/local/tomcat-test/admin-tomcat/webapps/image/会员表.xls", "Gyt12345.");
//                m_view.write("/Users/libing/Desktop/test/患者信息表.xls");
            } catch (Exception e) {
                e.printStackTrace();
            }
            ExcelTool.download("/usr/local/tomcat-test/admin-tomcat/webapps/image/会员表.xls", response);
//            ExcelTool.download("/Users/libing/Desktop/test/患者信息表.xls", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
